package com.myx.zookeeper.watcher;

import com.myx.zookeeper.ZookeeperSimpleConstant;
import com.myx.zookeeper.comm.CommCrud;
import lombok.Data;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * 描述:zk监听相关api
 * @author: myx
 * @date: 2018/11/17
 * Copyright © 2018-hotpot. All rights reserved.
 */
@Data
public class ZookeeperWatcher implements Watcher{
    //通用操作对象
    private CommCrud commCrud;
    /**
     * 构造器
     */
    public ZookeeperWatcher() {
        try {
            commCrud=new CommCrud(new ZooKeeper(ZookeeperSimpleConstant.connectString,5000,this));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent event) {
        // 连接状态
        Event.KeeperState keeperState = event.getState();
        // 事件类型
        Event.EventType eventType = event.getType();
        // 受影响的path
        String path = event.getPath();
        //step 1:只能监控一次
//        System.out.println("连接状态:"+keeperState+",事件类型："+eventType+",受影响的path:"+path);

        //step:2:循环监控
        try {
            //每进来一次都会重新监听
            if(null!=commCrud.exists("/myx",true)) {
                System.out.println("内容:"+ commCrud.getData("/myx", true));
            }
            System.out.println("连接状态:"+keeperState+",事件类型："+eventType+",受影响的path:"+path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("--------------------");
    }
}
